package com.example.myapplication.shop

import android.util.Log
import androidx.annotation.UiContext
import androidx.compose.foundation.Image
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.staggeredgrid.LazyVerticalStaggeredGrid
import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridCells
import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridItemSpan
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.material3.BadgedBox
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ScrollableTabRow
import androidx.compose.material3.Tab
import androidx.compose.material3.TabRow
import androidx.compose.material3.TabRowDefaults
import androidx.compose.material3.TabRowDefaults.tabIndicatorOffset
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.myapplication.R
import com.example.myapplication.common.ImageButton
import com.google.android.gms.common.logging.Logger
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch

@Composable
fun ShopScreen() {
    Column(modifier = Modifier.fillMaxSize()) {
        TopHeader()

        BodyContent()
    }
}

@Composable
fun TopHeader() {
    //获取输入框上面的字符串
    var textStr by remember {
        mutableStateOf("")
    }
    //获取输入框是否获取输入焦点
    var isFocused by remember {
        mutableStateOf(false)
    }

    // 获取焦点管理器和键盘控制器
    val focusManafocusManagerger = LocalFocusManager.current
    val keyboardController = LocalSoftwareKeyboardController.current

    Row(verticalAlignment = Alignment.CenterVertically) {
        Icon(
            painter = painterResource(R.drawable.login_title_icon),
            contentDescription = "",
            modifier = Modifier
                .padding(horizontal = 16.dp)
                .width(35.dp)
        )
        BasicTextField(
            value = textStr,
            //设置一个圆角的背景
            modifier = Modifier
                .weight(1.0f)
                .height(36.dp)
                .background(color = Color(0xFFF3F4F6), shape = RoundedCornerShape(4.dp))
                .onFocusChanged { state ->
                    isFocused = state.isFocused
                }, onValueChange = { str ->
                textStr = str
            }, keyboardActions = KeyboardActions(onDone = {
                focusManafocusManagerger.clearFocus()
                keyboardController?.hide()
            }), singleLine = true, decorationBox = { innerTextField ->
                Box() {
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        Icon(
                            painter = painterResource(R.drawable.shop_search_icon),
                            contentDescription = "",
                            modifier = Modifier
                                .padding(horizontal = 12.dp)
                                .size(14.dp)
                        )
                        Row(
                            modifier = Modifier.fillMaxSize(),
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            if (textStr.isEmpty() && !isFocused) {
                                Text(
                                    text = stringResource(R.string.searchShopItem),
                                    fontSize = 14.sp,
                                    color = Color(0xFF9CA3AF)
                                )
                            } else {
                                innerTextField()
                            }
                        }
                    }
                }
            })
        //如果是有角标的话，需要使用带角标的图标
        BadgedBox(badge = {
            // Box已经设置了contentAlignment = Alignment.Center,水平垂直居中
            // 但Text组件仍然是垂直方向偏向下的，此时需要设置《lineHeight = 12.sp,lineHeight与fontSize保持一致》
            Box(
                contentAlignment = Alignment.Center,
                modifier = Modifier
                    .offset(x = (-9).dp, y = (-5).dp)//这个购物数量的角标需要用类似的偏移位置
                    .size(16.dp)
                    .background(color = Color(0xFFFF6B6B), shape = RoundedCornerShape(8.dp))
            ) {
                Text("3", color = Color.White, fontSize = 12.sp, lineHeight = 12.sp)
            }
        }) {
            Icon(
                painter = painterResource(R.drawable.shopping_cart),
                contentDescription = "",
                modifier = Modifier
                    .padding(horizontal = 16.dp)
                    .width(23.dp)
                    .height(20.dp)
            )
        }
    }
}


@Composable
fun BodyContent() {
    var currentTabIndex by remember {
        mutableStateOf(1)
    }
    val pageState = rememberPagerState(initialPage = 1, pageCount = {
        val pageNum = 3
        pageNum
    })

    // scroll to page
    val coroutineScope = rememberCoroutineScope()

    val items = listOf<String>("特价", "首页", "新品")
    val itemWidth = LocalConfiguration.current.screenWidthDp * 0.333

    Log.e("screenWidth", "screenWidth is ${itemWidth}")

//    ScrollableTabRow(selectedTabIndex = currentTabIndex) {
//        items.forEachIndexed { index,item ->
//            Tab(selected = (index == currentTabIndex), modifier = Modifier.fillMaxWidth() ,onClick = {
//                currentTabIndex = index
//            }){
//                Box(modifier = Modifier.width(itemWidth.dp).height(40.dp).background(color = Color.Red), contentAlignment = Alignment.Center){
//                    Text(text = item)
//                }
//            }
//        }
//    }

    Column {
        TabRow(
            selectedTabIndex = currentTabIndex,
            //实现选择tabItem时底部的横线
            indicator = { tabPositions ->
                TabRowDefaults.SecondaryIndicator(
                    Modifier.tabIndicatorOffset(tabPositions[pageState.currentPage]),
                    color = Color(0xFFFF6B6B)
                )
            }, modifier = Modifier.padding(vertical = 10.dp)
        ) {
            //TabRow的tabs内容
            items.forEachIndexed { index, item ->
                Tab(
                    selected = (index == currentTabIndex),
                    modifier = Modifier.fillMaxWidth(),
                    selectedContentColor = Color(0xFFFF6B6B),
                    unselectedContentColor = Color(0xFF4B5563),
                    onClick = {
                        currentTabIndex = index

                        //TabRow点击tabs某个item时，跟随切换底部需要展示的内容
                        coroutineScope.launch {
                            // Call scroll to on pagerState
                            pageState.animateScrollToPage(currentTabIndex)
                        }

                    }) {
                    Box(
                        modifier = Modifier
                            .width(itemWidth.dp)
                            .height(40.dp),
                        contentAlignment = Alignment.Center
                    ) {
                        Text(text = item)
                    }
                }
            }
        }

        HorizontalPager(state = pageState) { page ->
            Column(modifier = Modifier.fillMaxSize()) {
                //switch-case的替换方案，根据具体的page展示不同的内容
                when (page) {
                    0 -> PromotionContent(page)
                    1 -> HomeContent(page)
                    2 -> NewProductContent(page)
                    else -> Box {}
                }
            }
        }
    }
}

//特价
@Composable
fun PromotionContent(page: Int) {
    Text("当前页面是${page}页")
}

//首页
@Composable
fun HomeContent(page: Int) {
    HotRecommend()
}

//热门推荐
@Composable
fun HotRecommend() {
    //商品之间的间隔为12.dp
    val gridItemsHorizonMarginSpacer = 12
    //热门推荐区域之间的内间距
    val gridsViewPadding = 16
    val gridItemWidth =
        (LocalConfiguration.current.screenWidthDp - gridsViewPadding * 2 - gridItemsHorizonMarginSpacer) * 0.5f;
    Log.e("gridItemWidth", "gridItemWidth is ${gridItemWidth}")

    /**
     * 1. LazyVerticalStaggeredGrid的内容项有哪两种？
     * item和item(num)
     * 其中item是一个Fulline类型的，占据一行的，这里面的相当于将bannerView,5个商品品类view，以及其它view组件都包含在里面了
     * item(num)是具体的网格items的具体实现，这边的一个问题就是要设置好瀑布流布局的item的左右间距问题。
     *
     * 2. 如何设置好瀑布流item之间的间距问题？
     * 第一步就是设置grid item水平之间的间距为16.dp，相当于item的marginLeft和marginRight都设置为16.dp（设置HotRecommendGridItem里Column的modifier.padding(horizontal = 16.dp)来实现）。设置完成之后，一行里的2个item的间距显示效果如下:
     * item的水平方向的间距为16，例如item1的左间距和右间距都为16，item2的左间距和右间距都为16，这样item1和item2之间的间距就是32，如下所示:
     * |---16-item1-16-16-item2-16---|
     * 但按照需求，item1 和 item2之间的间距应该为12.dp就行了，现在为32，足足多了20.dp出来
     *
     * 3.如何解决item1和item2之间的间距问题？如何调整为12.dp？
     * items之间水平的间距是通过LazyVerticalStaggeredGrid的horizontalArrangement来表示，通过实验，这个属性的值是支持负数的。
     * 32不符合我们的期望，我们希望的是item1和item2之间的间距为12，因此需要设置， 32 + （-20） = 12.dp
     * 因此，需要设置horizontalArrangement = Arrangement.spacedBy((-20).dp)就可以了
     */
    LazyVerticalStaggeredGrid(
        modifier = Modifier.background(color = Color.White),
        columns = StaggeredGridCells.Adaptive(gridItemWidth.dp),
        verticalItemSpacing = 12.dp,
        horizontalArrangement = Arrangement.spacedBy((-20).dp),
        content = {
            item(span = StaggeredGridItemSpan.FullLine) {
                Column(modifier = Modifier.fillMaxWidth()) {

                    //Todo : 图片轮播图
                    Image(
                        painter = painterResource(R.drawable.home_banner),
                        contentDescription = "",
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(180.dp),
                        contentScale = ContentScale.FillBounds
                    )

                    Row(
                        modifier = Modifier
                            .padding(vertical = 16.dp)
                            .fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceEvenly
                    ) {
                        ImageButton(
                            imageId = R.drawable.shop_category_clothes,
                            contentDescription = "clothes",
                            modifier = Modifier
                                .width(55.8.dp)
                                .height(68.dp),
                            onClick = {
                                Log.e("shop", "clothes")
                            })

                        ImageButton(
                            imageId = R.drawable.shop_category_digital,
                            contentDescription = "digital",
                            modifier = Modifier
                                .width(55.8.dp)
                                .height(68.dp),
                            onClick = {
                                Log.e("shop", "digital")
                            })

                        ImageButton(
                            imageId = R.drawable.shop_category_food,
                            contentDescription = "food",
                            modifier = Modifier
                                .width(55.8.dp)
                                .height(68.dp),
                            onClick = {
                                Log.e("shop", "food")
                            })

                        ImageButton(
                            imageId = R.drawable.shop_category_markup,
                            contentDescription = "markup",
                            modifier = Modifier
                                .width(55.8.dp)
                                .height(68.dp),
                            onClick = {
                                Log.e("shop", "markup")
                            })

                        ImageButton(
                            imageId = R.drawable.shop_category_house,
                            contentDescription = "house",
                            modifier = Modifier
                                .width(55.8.dp)
                                .height(68.dp),
                            onClick = {
                                Log.e("shop", "house")
                            })
                    }

                    //间隔线
                    Spacer(
                        modifier = Modifier
                            .height(8.dp)
                            .fillMaxWidth()
                            .background(color = Color(0xFFF7F8FA))
                    )

                    //热门推荐文本
                    Text(
                        stringResource(R.string.hotRecommend),
                        color = Color.Black,
                        fontSize = 18.sp,
                        modifier = Modifier.padding(top = 16.dp, start = 16.dp)
                    )
                }
            }

            items(10) { index ->
                HotRecommendGridItem(gridItemWidth, index)
            }
        })
}

@Composable
fun HotRecommendGridItem(gridItemWidth: Float, itemIndex: Int) {
    Column(
        modifier = Modifier
            .padding(
                horizontal = 16.dp
            )
            .width(gridItemWidth.dp)
            //如何给一个背景设置一个阴影效果，需要设置shadow，并且设置背景为白色
            .shadow(elevation = 3.dp, shape = RoundedCornerShape(8.dp))
            .background(color = Color.White)
    ) {
        Image(
            painter = painterResource(R.drawable.hot_recommend_goods1),
            contentDescription = "耳机",
            contentScale = ContentScale.FillWidth,
            modifier = Modifier.width(gridItemWidth.dp)
        )
        Text(
            if (itemIndex % 2 == 0) "新款无线蓝牙耳机 主动 降噪 超长续航 高清音质" else "新款无线蓝牙耳机 主动 降噪 超长续航 高清音质 主动 降噪 超长续航 高清音质 高清音质 高清音质 新款无线蓝牙耳机",
            fontSize = 14.sp,
            modifier = Modifier
                .padding(top = 8.dp)
                .padding(horizontal = 8.dp)
        )
        Row(
            modifier = Modifier
                .padding(vertical = 8.dp)
                .fillMaxWidth()
                .padding(horizontal = 8.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text("¥ ${299}", color = Color(0xFFFF6B6B), fontSize = 14.sp)
            Box(modifier = Modifier.weight(1.0f))
            ImageButton(
                R.drawable.add_to_card_icon, Modifier.size(32.dp), "添加到购物车", onClick = {

                })
        }
    }
}

//新品
@Composable
fun NewProductContent(page: Int) {
    Text("当前页面是${page}页")
}